package com.youlu.campus.admin.utils.excel;

import com.alibaba.excel.context.AnalysisContext;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 * 验证 EasyExcel监听器
 *
 * @param <T>
 */
public class ValidateExcelListener<T> extends ExcelListener<T> {

    @Override
    public void invoke(T data, AnalysisContext context) {
        // 手动验证数据
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<T>> violations = validator.validate(data);

        if (!violations.isEmpty()) {
            success = false;
            int errorRow = context.readRowHolder().getRowIndex() + 1;
            StringBuilder sb = new StringBuilder();
            sb.append("第").append(errorRow).append("行数据错误: ");
            for (ConstraintViolation<T> violation : violations) {
                sb.append(violation.getMessage()).append(";");
            }
            errorMessages.add(sb.toString());
            errorRows.add(errorRow);
        } else {
            dataList.add(data);
        }
    }

    public void doAfterAllAnalysed(AnalysisContext context) {

    }
}